package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserClient;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ICommentServiceImpl implements ICommentService {

    @Autowired
    UserClient userClient;

    @Autowired
    MongoTemplate mongoTemplate;

    //发布评论
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //评论内容不大于140字
        if (dto == null || StringUtils.isEmpty(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //要求用户登录才能评论
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //评论内容需要审核 todo 对接阿里云文本安全
        //构建评论实体
        ApComment comment = new ApComment();
        comment.setAuthorId(user.getUserId());
        //方案一：在用户登录是时将用户的信息放入到token中
        //方案二：更具用户id查询用户信息，需要用户服务提供接口
        ResponseResult<ApUser> responseResult = userClient.getUserById(user.getUserId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = responseResult.getData();
            comment.setAuthorName(apUser.getName());
            comment.setImage(apUser.getImage());
        }
        comment.setEntryId(dto.getArticleId());
        comment.setType(0);
        comment.setContent(dto.getContent());
        comment.setLikes(0);
        comment.setReply(0);
        comment.setFlag(0);
        comment.setCreatedTime(new Date());
        //保存评论到MongoDB
        mongoTemplate.save(comment);
        return ResponseResult.okResult();
    }

    //评论点赞
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //要求用户登录才能评论
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建点赞记录
        ApCommentLike commentLike = new ApCommentLike();
        commentLike.setAuthorId(user.getUserId());
        commentLike.setCommentId(dto.getCommentId());
        commentLike.setOperation(dto.getOperation());
        //判断当前用户是否对当前评论有过记录
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        //如果没有，新增记录
        if (one == null) {
            if (dto.getOperation() == 0) {
                mongoTemplate.save(commentLike);
                //将评论表中的点赞数+1
                Query queryComment = new Query();
                queryComment.addCriteria(Criteria.where("id").is(dto.getCommentId()));
                Update update = new Update();
                update.inc("likes");
                mongoTemplate.updateFirst(queryComment,update,ApComment.class);
            }
        } else {
            int add = 1;
            //如果有，修改点赞的状态,判断状态不一致，进行更新
            if (one.getOperation() != dto.getOperation()) {
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                if (dto.getOperation() == 1) {
                    add = -1;
                }
                //将评论表中的点赞数更新
                Query queryComment = new Query();
                queryComment.addCriteria(Criteria.where("id").is(dto.getCommentId()));
                Update update = new Update();
                update.inc("likes",add);
                mongoTemplate.updateFirst(queryComment,update,ApComment.class);
            }
        }
        return ResponseResult.okResult();
    }

    //评论列表
    @Override
    public ResponseResult load(CommentDto dto) {
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
       //根据文章分页查询评论
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        //分页查询时间小于前端传递的最小时间
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        Pageable pageable = PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"createdTime");
        query.with(pageable);
        List<ApComment> comments = mongoTemplate.find(query, ApComment.class);
        //判断当前用户是否在评论列表中点赞了，如果点在了，需要高亮显示
        List<ApCommentVo> vos = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (ApComment comment : comments) {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(comment,vo);
            vo.setOperation(1);
            vos.add(vo);
            ids.add(comment.getId());
        }
        //获取当前登录的用户
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            //查询当前评论列表对对应的点赞记录
            Query queryLike = new Query();
            queryLike.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            queryLike.addCriteria(Criteria.where("commentId").in(ids));
            queryLike.addCriteria(Criteria.where("operation").is(0));
            List<ApCommentLike> apCommentLikes = mongoTemplate.find(queryLike, ApCommentLike.class);
            //获取所有当前用户点赞过的评论id
            List<String> likeIds = new ArrayList<>();
            for (ApCommentLike commentLike : apCommentLikes) {
                likeIds.add(commentLike.getCommentId());
            }
            //对结果进行处理
            for (String likeId : likeIds) {
                for (ApCommentVo vo : vos) {
                    if (vo.getId().equals(likeId)) {
                        vo.setOperation(0);
                    }
                }
            }
        }
            return ResponseResult.okResult(vos);
    }
}
